package com.example.Controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.dao.TypeNameMapper;
import com.example.dao.UserMapper;

import com.example.dao.WeekendMapper;
import com.example.pojo.TypeName;
import com.example.pojo.User;
import com.example.pojo.Weekend;
import com.example.util.Result;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.DecimalFormat;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.Map;

@Api(tags = "请假管理")
@CrossOrigin
@RestController
public class WeekendController {

    @Autowired
    private WeekendMapper weekendMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private TypeNameMapper typeNameMapper;


    @RequestMapping("/selectWeekendBy")//根据状态查询
    public Result selectWeekendBy(Integer state){
        QueryWrapper<Weekend> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("creat_time");
        if (state == 10){
            queryWrapper.ne("status", 1);
        }else {
            queryWrapper.eq("status", state);
        }

        List<Weekend>weekends=weekendMapper.selectList(queryWrapper);
        List<Weekend> weekendList=new ArrayList<>();
        for (Weekend weekend : weekends) {
            //请假人信息
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("id", weekend.getUserId());
            User user=userMapper.selectOne(userQueryWrapper);
            weekend.setUser(user);
            //批改人信息
            QueryWrapper<User> userQueryWrapper1 = new QueryWrapper<>();
            userQueryWrapper1.eq("id", weekend.getUpdateBy());
            User user1=userMapper.selectOne(userQueryWrapper1);
            weekend.setUser1(user1);
            //部门信息
            QueryWrapper<TypeName> typeNameQueryWrapper = new QueryWrapper<>();
            typeNameQueryWrapper.eq("id", weekend.getTypeDate());
            TypeName typeName=typeNameMapper.selectOne(typeNameQueryWrapper);
            weekend.setTypeName(typeName);
//            long daysBetween = ChronoUnit.DAYS.between(weekend.getStartTime(),weekend.getEndTime());
            // 计算两个时间点之间的持续时间
            Duration duration = Duration.between(weekend.getStartTime(),weekend.getEndTime());
            // 将持续时间转换为小时数（带小数）
            double hours = duration.getSeconds() / 3600.0; // 总秒数除以 3600（一小时的秒数）
            // 精确到小数点后一位并四舍五入
            double roundedHours = Math.round(hours * 10) / 10.0;
            DecimalFormat decimalFormat = new DecimalFormat("#.##");
            String formattedHours = decimalFormat.format(roundedHours);
            // 将持续时间转换为天数（带小数）
            double days = duration.getSeconds() / (24.0 * 60 * 60); // 总秒数除以一天的秒数
            double daysBetween=Math.ceil(days * 10) / 10.0;
            String formDaysBetween = decimalFormat.format(daysBetween);
            String time;
            if (hours>=24){
                time=formDaysBetween+"天";
            }else {
                time=formattedHours+"小时";
            }
            weekend.setTime(time);
            if (user.getPositionId()<4||daysBetween>=5)weekendList.add(weekend);
        }
        return new Result("200","获取请假",weekendList);
    }
    @RequestMapping("/selectWeekendCountByState")//根据状态查询数量
    public Object selectWeekendCountByState(Integer state){
        QueryWrapper<Weekend> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", state);
        List<Weekend> weekendList= weekendMapper.selectList(queryWrapper);
        List<Weekend> weekends =new ArrayList<>();
        for (Weekend weekend : weekendList) {
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("id", weekend.getUserId());
            User user=userMapper.selectOne(userQueryWrapper);
            weekend.setUser(user);
            long daysBetween = ChronoUnit.DAYS.between(weekend.getStartTime(),weekend.getEndTime());
            if (user.getPositionId()<4||daysBetween>=5)weekends.add(weekend);
        }
        Map<Integer, Integer> statusCountMap = weekends.stream()
            .collect(Collectors.groupingBy(
            Weekend::getStatus,
            Collectors.mapping(weekend -> 1, Collectors.summingInt(Integer::intValue))
        ));
        return new Result("200", "请假数量", statusCountMap);
    }
    @RequestMapping("/updateStatusById")//根据id修改状态
    public Object updateStatusById(@RequestBody Weekend weekend){
        return new Result("200", "请假数量",weekendMapper.updateById(weekend));
    }
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    //             楚河·汉界
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    @RequestMapping("/insertWeek")//申请请假
    public Result selectSelfDe(@RequestBody Weekend weekend){
        int insert = weekendMapper.insert(weekend);
        return new Result("200","添加成功",insert);
    }

    @RequestMapping("/sectWeek")//查询自己
    public Result sectWeek(Integer userId){
        QueryWrapper<Weekend> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        List<Weekend> weekends = weekendMapper.selectList(wrapper);
        return new Result("200","查询成功",weekends);
    }

    @RequestMapping("/selectAllW")  //查询全部
    public Result selectAllW(Integer userId){

        User user = userMapper.selectOne(userId); //当前的权限对象
        List<Weekend> weekends = weekendMapper.selectList(null);  //全部的请假记录
        List<Weekend> weekendList = new ArrayList<>();
        if (weekends != null && !weekends.isEmpty()) {

            for (int i = 0; i < weekends.size(); i++) {
                Weekend weekend = weekends.get(i);
                Integer userI = weekend.getUserId();
                if (userI != null) {
                    try {
                        User user1 = userMapper.selectOne(userI);
                        if(user1.getPositionId()>user.getPositionId()&&(user1.getDepartmentId()==user.getDepartmentId())){ //判断权限和部门
                            LocalDateTime startTime = weekend.getCreatTime();
                            LocalDateTime endTime = weekend.getEndTime();

                            // 计算两个时间之间的差异
                            Duration duration = Duration.between(startTime, endTime);

                            // 将差异转换为小时数
                            long hoursBetween = duration.toHours();

                            // 判断小时数是否大于5
                            if (hoursBetween < 120) {
                                weekendList.add(weekend);
                            }
                        }
                    } catch (Exception e) {
                        // 处理异常，例如记录日志
                        e.printStackTrace();
                    }
                }
            }
        }
        return new Result("200","查询成功",weekendList);
    }

    @RequestMapping("/updateInfo")//请假审批
    public Result updateInfo(Integer id,Integer status,String remark,String updateBy){

        QueryWrapper<Weekend> wrapper =new QueryWrapper<>();
        wrapper.eq("id",id);
        Weekend weekend = weekendMapper.selectOne(wrapper);
        weekend.setStatus(status);
        weekend.setRemark(remark);
        weekend.setUpdateBy(updateBy);
        int update = weekendMapper.update(weekend, wrapper);

        return new Result("200","修改成功",update);
    }
}
